<?php
use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Lib\Timer;
use PHPSocketIO\SocketIO;

include __DIR__ . '../../vendor/autoload.php';

$uid_arr = array();  //在线用户

// PHPSocketIO服务
$sender_io = new SocketIO(3324);
//连接
$sender_io->on('connection', function($socket) {
    //在线
    $socket->on('online', function ($uid,$ip)use($socket){
        //记录当前用户ip 和登录时间  并将其写入文本  并返回在线当前人数
        global  $uid_arr;
        if(isset($socket->uid)){
            return;
        }
        $socket->uid = $uid;
        $uid_arr[$socket->uid] = count($uid_arr)+1;
        $text = $uid.'-'.date('Y-m-d H:i'). "-" . $ip . "\r\n";
        file_put_contents('uid-ip-online.txt',$text,FILE_APPEND);
        $socket->emit('total-users',"当前在线用户 ".count($uid_arr));
    });


    //断开连接
    $socket->on('disconnect', function () use($socket){
        if(!isset($socket->uid))
        {
            return;
        }
        global $uid_arr;
        unset($uid_arr[$socket->uid]);
    });

});


//启动
$sender_io->on('workerStart', function(){

    //监听3726端口发送的消息
    $inner_http_worker = new Worker('http://0.0.0.0:3726');
    $inner_http_worker->onMessage = function($http_connection, $data){

        return $http_connection->send('hello');
    };
    $inner_http_worker->listen();


    // 定时器，推送在线用户数量
    Timer::add(1, function(){
        global $uid_arr, $sender_io;
        $sender_io->emit('total-users',"当前在线用户 ".count($uid_arr));
    });
});

Worker::runAll();